{
 "cells": [
  {
   "metadata": {
    "collapsed": true
   },
   "cell_type": "markdown",
   "source": [
    "# Lesson3 Python流程控制\n",
    "\n",
    "## 程序的流程控制\n",
    "\n",
    "- 顺序结构：代码自上而下，逐行执行\n",
    "- 分支结构：根据条件，分情况执行\n",
    "- 循环结构：根据条件，重复执行\n",
    "\n",
    "## 导入模块\n",
    "\n",
    "- Python 使用 import 导入非内置的模块。\n",
    "- 常用的写法：\n",
    "  - 将某个模块整个导入：import 模块 。导入后需要使用\"模块名.函数名()\"调用函数。\n",
    "  - 将某个模块整个导入：import 模块 as 别名。导入后需要使用\"模块别名.函数名()\"调用函数。\n",
    "  - 将某个模块的所有函数导入：from 模块 import *。导入后直接使用\"函数名()\"调用函数。\n",
    "  - 将某个模块的某个函数导入：from 模块 import 函数。导入后直接使用\"函数名()\"调用函数。\n",
    "  - 将某个模块的某些函数导入：from 模块 import 函数1, 函数2, ..., 函数n。导入后直接使用\"函数名()\"调用函数。\n",
    "- 建议使用 import ... 方法导入，使用 from ... import ... 可能会导致函数名冲突。\n",
    "\n",
    "## 生成随机数\n",
    "\n",
    "- 导入 random 库。`import random`\n",
    "- `random.randint(a,b)` 生成一个大于等于a且小于等于b的随机整数\n",
    "- `random.randrange(a,b)` 生成一个大于等于a且小于b的随机整数\n",
    "- `random.random()` 生成一个大于等于0且小于1之间的随机浮点数\n",
    "- `random.uniform(a,b)` 生成一个a和b之间（包含a和b）的随机浮点数\n",
    "\n",
    "### 例子：加法题\n"
   ],
   "id": "7d6acf1bcc74764d"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-12T03:26:12.067146Z",
     "start_time": "2025-09-12T03:26:00.107717Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# AdditionQuiz.py\n",
    "import random\n",
    "\n",
    "# Generate random numbers\n",
    "number1 = random.randint(0, 9)\n",
    "number2 = random.randint(0, 9)\n",
    "\n",
    "# Prompt the user to enter an answer\n",
    "answer = eval(input(\"What is \" + str(number1) + \" + \"\n",
    "    + str(number2) + \"? \"))\n",
    "\n",
    "# Display result\n",
    "print(number1, \"+\", number2, \"=\", answer,\n",
    "    \"is\", number1 + number2 == answer)"
   ],
   "id": "f8fc5db3b2b34b16",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "6 + 0 = 6 is True\n"
     ]
    }
   ],
   "execution_count": 1
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "## 分支结构\n",
    "\n",
    "- if语句。使用if语句可以进行条件判断，根据结果选择不同的运行分支。\n",
    "- if语句的三种形式：if、if...else、if...elif...else\n",
    "- 缩进：同一个代码段层次，需要相同的缩进，一般为4个空格，有些人喜欢用1个Tab。官方建议缩进使用4个空格。Python用缩进表达代码段的范围。\n",
    "- pass语句：空语句，什么也不做，用于避免程序逻辑错误。\n",
    "```\n",
    "cond1 = cond2 = False\n",
    "if cond1:\n",
    "    pass\n",
    "\n",
    "if cond1:\n",
    "    pass\n",
    "else:\n",
    "    pass\n",
    "\n",
    "if cond1:\n",
    "    pass\n",
    "elif cond2:\n",
    "    pass\n",
    "else:\n",
    "    pass\n",
    "```"
   ],
   "id": "2462806224d7cc20"
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "### 例子：生肖年",
   "id": "cc888e937ce71372"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-13T03:37:08.346959Z",
     "start_time": "2025-09-13T03:37:02.420296Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# ChineseZodiac.py\n",
    "year = eval(input(\"Enter a year: \"))\n",
    "zodiacYear = year % 12\n",
    "if zodiacYear == 0:\n",
    "    print(\"monkey\")\n",
    "elif zodiacYear == 1:\n",
    "    print(\"rooster\")\n",
    "elif zodiacYear == 2:\n",
    "    print(\"dog\")\n",
    "elif zodiacYear == 3:\n",
    "    print(\"pig\")\n",
    "elif zodiacYear == 4:\n",
    "    print(\"rat\")\n",
    "elif zodiacYear == 5:\n",
    "    print(\"ox\")\n",
    "elif zodiacYear == 6:\n",
    "    print(\"tiger\")\n",
    "elif zodiacYear == 7:\n",
    "    print(\"rabbit\")\n",
    "elif zodiacYear == 8:\n",
    "    print(\"dragon\")\n",
    "elif zodiacYear == 9:\n",
    "    print(\"snake\")\n",
    "elif zodiacYear == 10:\n",
    "    print(\"horse\")\n",
    "else:\n",
    "    print(\"sheep\")"
   ],
   "id": "fdb5a9a6c2b67283",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "ox\n"
     ]
    }
   ],
   "execution_count": 3
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "### 例子：成绩等级\n",
    "- 知识点：复合条件。如果想表示条件为：score大于等于80而且小于90\n",
    "```\n",
    " score >= 80 and score < 90\t\t# 正确，且在别的语言，如C语言，也可以这样写\n",
    " 80 <= score and score < 90\t\t# 正确，且在别的语言，如C语言，也可以这样写\n",
    " 80 <= score < 90\t\t\t\t# Python中正确，但是在别的语言，如C语言中，是错误的\n",
    "```"
   ],
   "id": "3a25e4e9a506a24e"
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "- if语句嵌套",
   "id": "1da17df6339b3665"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-13T03:40:10.866004Z",
     "start_time": "2025-09-13T03:40:07.543881Z"
    }
   },
   "cell_type": "code",
   "source": [
    "score = eval(input(\"Enter the score: \"))\n",
    "if score >= 90:\t\t\t\t\t# 90 <= score and score <= 100\n",
    "    grade = 'A'\n",
    "else:\n",
    "    if score >= 80:\t\t\t\t# 80 <= score and score < 90\n",
    "        grade = 'B'\n",
    "    else:\n",
    "        if score >= 70:\t\t\t# 70 <= score and score < 80\n",
    "            grade = 'C'\n",
    "        else:\n",
    "            if score >= 60:\t\t# 60 <= score and score < 70\n",
    "                grade = 'D'\n",
    "            else:\t\t\t\t# 0 <= score and score < 60\n",
    "                grade = 'F'\n",
    "print(grade)"
   ],
   "id": "243a753b528f3996",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "C\n"
     ]
    }
   ],
   "execution_count": 4
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "- 多分支if语句",
   "id": "81033b607b53dbd6"
  },
  {
   "metadata": {},
   "cell_type": "code",
   "outputs": [],
   "execution_count": null,
   "source": [
    "score = eval(input(\"Enter the score: \"))\n",
    "if score >= 90:\t\t# 90 <= score <= 100\n",
    "    grade = 'A'\n",
    "elif score >= 80:\t# 80 <= score < 90\n",
    "    grade = 'B'\n",
    "elif score >= 70:\t# 70 <= score < 80\n",
    "    grade = 'C'\n",
    "elif score >= 60:\t# 60 <= score < 70\n",
    "    grade = 'D'\n",
    "else:\t\t\t\t# 0 <= score < 60\n",
    "    grade = 'F'\n",
    "print(grade)"
   ],
   "id": "5e25a85d86ae2536"
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "- 多分支if语句的错误示例",
   "id": "1306d2e032cac711"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-13T03:41:32.128921Z",
     "start_time": "2025-09-13T03:41:27.316249Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 以下为错误代码！\n",
    "score = eval(input(\"Enter the score: \"))\n",
    "if score >= 60:\n",
    "    grade = 'D'\n",
    "elif score >= 70:\n",
    "    grade = 'C'\n",
    "elif score >= 80:\n",
    "    grade = 'B'\n",
    "elif score >= 90:\n",
    "    grade = 'A'\n",
    "else:\n",
    "    grade = 'F'\n",
    "print(grade)"
   ],
   "id": "e23ed7a9b50d3443",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "D\n"
     ]
    }
   ],
   "execution_count": 5
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "## <font color='red'> 思考： python是否有类似于C语言的switch case语句？ </font>",
   "id": "70f3f09092e1e2a3"
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "### 例子：计算 BMI 并给出建议",
   "id": "670a16463a5a6d7a"
  },
  {
   "metadata": {},
   "cell_type": "code",
   "source": [
    "# ComputeBMI.py\n",
    "# Prompt the user to enter weight in kilograms\n",
    "weight = eval(input(\"Enter weight in kilograms: \"))\n",
    "\n",
    "# Prompt the user to enter height in meters\n",
    "height = eval(input(\"Enter height in meters: \"))\n",
    "\n",
    "# Compute BMI\n",
    "bmi = weight / (height * height)\n",
    "\n",
    "# Display result\n",
    "print(\"BMI is\", format(bmi, \".2f\"))\n",
    "if bmi < 18.5:\n",
    "    print(\"Underweight\")\n",
    "elif bmi < 25:\n",
    "    print(\"Normal\")\n",
    "elif bmi < 30:\n",
    "    print(\"Overweight\")\n",
    "else:\n",
    "    print(\"Obese\")"
   ],
   "id": "288bfc4f2429292",
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "### 例子：判断某年是否为闰年\n",
    "\n",
    "- 现行为主流历法为格里高利历，其置闰规则为：\n",
    "  - 一般情况（非世纪年），如果年份数除以4可以除得尽，则置闰，即2月有29天，全年有366天。\n",
    "  - 特殊情况（世纪年：即最后两位为00的年份），如果年份数除以400可以除得尽，则置闰，即2月有29天，全年有366天。\n",
    "  - 其它情况，为平年，不置闰，即2月有28天，全年有365天\n",
    "- 为什么要置闰？\n",
    "  - 经天文测量，目前一回归年约为365.2422天。\n",
    "  - 如果不置闰年，则一年有365天，误差为0.2422天/年。\n",
    "  - 如果不处理世纪年，则一年有365.25天，误差为0.0078天/年。\n",
    "  - 如果处理世纪年，则一年有365.2425天，误差为0.0003天/年。"
   ],
   "id": "917aa407010da202"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-28T05:48:52.097997400Z",
     "start_time": "2025-09-13T03:56:33.591488Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# LeapYear.py\n",
    "year = eval(input(\"Enter a year: \"))\n",
    "\n",
    "# Check if the year is a leap year\n",
    "# method 1\n",
    "isLeapYear = False\n",
    "if year % 100 == 0:\n",
    "    if year % 400 == 0:\n",
    "        isLeapYear = True\n",
    "else:\n",
    "    if year % 4 == 0:\n",
    "        isLeapYear = True\n",
    "\n",
    "# method 2\n",
    "isLeapYear = (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)\n",
    "\n",
    "# Display the result\n",
    "print(year, \"is a leap year?\", isLeapYear)"
   ],
   "id": "c1d3b244adf2bac8",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1900 is a leap year? False\n"
     ]
    }
   ],
   "execution_count": 13
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "- 小知识：历史上消失的11天\n",
    "\n",
    "### 例子：求一个月的天数\n",
    "\n",
    "- 如果想判断月份 month 是小月\n",
    "```\n",
    "month == 4 or 6 or 9 or 11 # 错误！6意为True\n",
    "month == 4 or month == 6 or month == 9 or month == 11 # 正确，代码较长\n",
    "month in (4,6,9,11) # 正确，使用元组更简练\n",
    "```"
   ],
   "id": "db89b28e4e2b52b6"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-28T05:48:52.104878700Z",
     "start_time": "2025-09-13T04:01:40.092912Z"
    }
   },
   "cell_type": "code",
   "source": [
    "year = eval(input(\"Enter a year: \"))\n",
    "month = eval(input(\"Enter a month: \"))\n",
    "\n",
    "if month == 2:\n",
    "    if year % 400 == 0 or year % 100 !=0 and year % 4 == 0:\n",
    "        days = 29  # 闰年，2月为29天\n",
    "    else:\n",
    "        days = 28  # 平年，2月为28天\n",
    "\n",
    "elif month in (1,3,5,7,8,10,12):\n",
    "    days = 31\n",
    "\n",
    "elif month == 4 or month == 6 or month == 9 or month == 11:\n",
    "    days = 30\n",
    "\n",
    "print(days)\n"
   ],
   "id": "8b378e28ff42f426",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "30\n"
     ]
    }
   ],
   "execution_count": 17
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "### 条件表达式\n",
    "\n",
    "- 类似于C语言中的三元运算符\n",
    "- 格式为：表达式1 if 条件 else 表达式2。当条件成立时，结果为表达式1，否则，结果为表达式2\n",
    "```\n",
    "x = eval(input())\n",
    "if x>=0:\n",
    "    y=1\n",
    "else:\n",
    "    y=-1\n",
    "\n",
    "# 等价的条件表达式\n",
    "\n",
    "y = 1 if x>=0 else -1\n",
    "```"
   ],
   "id": "23215b3269040a8"
  },
  {
   "metadata": {},
   "cell_type": "code",
   "outputs": [],
   "execution_count": null,
   "source": [
    "number = eval(input())\n",
    "\n",
    "# 判断 number 是否为偶数\n",
    "# 方法1\n",
    "if number % 2 == 0:\n",
    "    even = True\n",
    "else:\n",
    "    even = False\n",
    "if even:\n",
    "    print(\"number is even\")\n",
    "else:\n",
    "    print(\"number is odd\")\n",
    "\n",
    "# 方法2\n",
    "even = number % 2 == 0\n",
    "if even:\n",
    "    print(\"number is even\")\n",
    "else:\n",
    "    print(\"number is odd\")\n",
    "\n",
    "# 方法3\n",
    "print(\"number is even\" if number % 2 == 0 else \"number is odd\")"
   ],
   "id": "de61ef95e1be84c3"
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "### 例子：随机生成一个四则运算题",
   "id": "5b73ad06428b32fd"
  },
  {
   "metadata": {},
   "cell_type": "code",
   "outputs": [],
   "execution_count": null,
   "source": [
    "import random\n",
    "\n",
    "n1 = random.randint(1,9)\n",
    "n2 = random.randint(1,9)\n",
    "\n",
    "method = random.randint(1,4)\n",
    "\n",
    "if method == 1: # 出加法题\n",
    "     print(n1, \"+\", n2, \"=?\")\n",
    "     answer = int(input())\n",
    "     if answer == n1+n2:\n",
    "           print(\"回答正确\")\n",
    "     else:\n",
    "           print(\"回答错误，正确答案是\", n1 + n2)\n",
    "elif method == 2: # 出减法题\n",
    "     if n1 < n2:\n",
    "          n1,n2 = n2, n1\n",
    "     print(n1, \"-\", n2, \"=?\")\n",
    "     answer = int(input())\n",
    "     if answer == n1-n2:\n",
    "           print(\"回答正确\")\n",
    "     else:\n",
    "           print(\"回答错误，正确答案是\", n1 - n2)\n",
    "elif method == 3:  # 出乘法题\n",
    "     print(n1, \"*\", n2, \"=?\")\n",
    "     answer = int(input())\n",
    "     if answer == n1*n2:\n",
    "           print(\"回答正确\")\n",
    "     else:\n",
    "           print(\"回答错误，正确答案是\", n1 * n2)\n",
    "else:  # 出除法题\n",
    "     n3 = n1 * n2\n",
    "     print(n3, \"/\", n1, \"=?\")\n",
    "     answer = int(input())\n",
    "     if answer == n2:\n",
    "           print(\"回答正确\")\n",
    "     else:\n",
    "           print(\"回答错误，正确答案是\", n2)"
   ],
   "id": "ac0b01c4b1208ed"
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "## 循环结构\n",
    "\n",
    "### while语句\n",
    "\n",
    "- 遇到while语句时，如果条件成立，while执行循环体中的语句\n",
    "- 执行完每一轮循环后，while会重新判断条件，如果条件仍然成立，则再次执行循环体中的语句\n",
    "```\n",
    "cond1 = True\n",
    "while cond1:\n",
    "    pass\n",
    "```"
   ],
   "id": "3e67da63b1b4f41f"
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "### 例子：从1累加到100求和",
   "id": "5d15e883d34fad70"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-13T04:10:27.667339Z",
     "start_time": "2025-09-13T04:10:27.663019Z"
    }
   },
   "cell_type": "code",
   "source": [
    "i=1\n",
    "sum=0\n",
    "while i<=100:\n",
    "\tsum += i\n",
    "\ti += 1\n",
    "print(sum)"
   ],
   "id": "e2ddde84eda286aa",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "5050\n"
     ]
    }
   ],
   "execution_count": 18
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "- 在执行到while语句时，条件如果为False，则直接跳过循环，执行循环之后的语句。\n",
    "- 在循环体中，必须有使条件判断结果发生变化的语句，否则循环将永远执行下去（称为死循环）。"
   ],
   "id": "7ff853d003ffe94b"
  },
  {
   "metadata": {},
   "cell_type": "code",
   "outputs": [],
   "execution_count": null,
   "source": [
    "x = eval(input())\n",
    "while x!= 0:\n",
    "    print(x)\n",
    "    x -= 3\n",
    "print(\"Finish.\")"
   ],
   "id": "e19b3acb0369e88"
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "### 例子：猜数字",
   "id": "8999fc3768cd5f67"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-13T04:12:10.643995Z",
     "start_time": "2025-09-13T04:11:26.925795Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# GuessNumber.py\n",
    "import random\n",
    "\n",
    "# Generate a random number to be guessed\n",
    "number = random.randint(1, 100)\n",
    "\n",
    "print(\"Guess a magic number between 1 and 100\")\n",
    "\n",
    "guess = -1\n",
    "while guess != number:\n",
    "    # Prompt the user to guess the number\n",
    "    guess = eval(input(\"Enter your guess: \"))\n",
    "\n",
    "    if guess == number:\n",
    "        print(\"Yes, the number is\", number)\n",
    "    elif guess > number:\n",
    "        print(\"Your guess is too high\")\n",
    "    else:\n",
    "        print(\"Your guess is too low\")"
   ],
   "id": "e5ff7a53883640ab",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Guess a magic number between 1 and 100\n",
      "Your guess is too high\n",
      "Your guess is too high\n",
      "Your guess is too high\n",
      "Your guess is too high\n",
      "Your guess is too low\n",
      "Yes, the number is 4\n"
     ]
    }
   ],
   "execution_count": 19
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "### for...in语句\n",
    "\n",
    "- for...in语句一般用于实现已经循环次数的循环。\n",
    "- 基本结构：for 变量 in 序列，循环执行的次数与序列中元素的个数相同，每次循环中，变量自动赋值为序列中的某个元素。"
   ],
   "id": "caa5f9faf7f78f82"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-13T04:13:06.691247Z",
     "start_time": "2025-09-13T04:13:06.687862Z"
    }
   },
   "cell_type": "code",
   "source": [
    "for c in 'hello':\t# 循环5次，依次输出 h, e, l, l, o 五个字母\n",
    "    print(c)\n",
    "\n",
    "for i in (2,3,5,7): # 循环4次，依次输出 2, 3, 5, 7 四个数字\n",
    "    print(i)"
   ],
   "id": "4c10dcd0ba6c7cc2",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "h\n",
      "e\n",
      "l\n",
      "l\n",
      "o\n",
      "2\n",
      "3\n",
      "5\n",
      "7\n"
     ]
    }
   ],
   "execution_count": 20
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "### range()函数\n",
    "\n",
    "- range()函数经常用在for...in语句中\n",
    "\n",
    "- range(n)：产生一个 0,1,2,3,....,n-1 这n个数的序列，注意是从0开始，总数为n个。\n",
    "\n",
    "  - 如果 n<= 0，生成的序列为空。\n",
    "\n",
    "  - 例：range(5)：产生 0,1,2,3,4 这 5 个数组成的序列\n",
    "\n",
    "- range(a,b)：产生从 a 到 b 的数字序列，注意是大于等于a且小于b，即包含 a 而不包含 b ！\n",
    "\n",
    "  - 如果b<=a，生成的序列为空。\n",
    "  - 例：range(1,10)：产生 1,2,3,...,9 这 9 个数的序列\n",
    "\n",
    "- range(a,b,k)函数：产生一个a,a+k,a+k+k,...序列，即从 a 开始向 b 行进，但不能达到 b，即：\n",
    "\n",
    "  - 如果 k>0，生成序列中的最大值不能大于或等于b。如果b<=a，生成的序列为空。\n",
    "  - 如果 k<0，生成序列中的最大值不能小于或等于b。如果b>=a，生成的序列为空。\n",
    "  - k不能等于0。省略参数 k，相当于 k=1\n",
    "  - 例：range(0,10,2)，将产生0,2,4,6,8这个序列\n",
    "  - 例：range(10,1,-1)，将产生10,9,8,7,6,5,4,3,2这个序列\n",
    "\n",
    "### 例题：二个年份之间多少天\n",
    "\n",
    "- 输入一个起始年份和一个终止年份，计算并输出一共有多少天？"
   ],
   "id": "f0c7b4e29486d08f"
  },
  {
   "metadata": {},
   "cell_type": "code",
   "outputs": [],
   "execution_count": null,
   "source": [
    "year1 = int(input())\n",
    "year2 = int(input())\n",
    "\n",
    "days = 0\n",
    "for i in range(year1,year2+1):\n",
    "    if i%400==0 or i%100!=0 and i%4==0:\n",
    "        days += 366\n",
    "    else:\n",
    "        days += 365\n",
    "\n",
    "print(days)"
   ],
   "id": "ac288d9d171ef811"
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "### while和for循环的转换\n",
    "\n",
    "- 一般来说，已知循环次数的情况，可以用for循环，也可以用while循环，且for循环往往比较简单。\n",
    "- 未知循环次数的情况，一般使用while循环。\n",
    "```python\n",
    "# 当已知循环次数时，可以使用以下两种循环方式\n",
    "# while 循环\n",
    "i = 1\n",
    "while i < n:\n",
    "    pass\n",
    "\ti += 1\n",
    "\n",
    "# for 循环\n",
    "for i in range(1,n):\n",
    "    pass\n",
    "```"
   ],
   "id": "3f6ed5039f710cd4"
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "### 不要比较浮点数\n",
    "\n",
    "- 例如：计算 1+0.9+0.8……+0.2+0.1"
   ],
   "id": "868fccf5838de32c"
  },
  {
   "metadata": {},
   "cell_type": "code",
   "source": [
    "item = 1\n",
    "sum = 0\n",
    "\n",
    "while item != 0:\t# 死循环，无法退出\n",
    "    sum += item\n",
    "    item -= 0.1\n",
    "    print(item)\n",
    "\n",
    "print(sum)"
   ],
   "id": "4c7f427bb90abcc8",
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "- 不用等于来判，那么改成小于等于行不行？\n",
    "- 再例：求和。0.01 + 0.02 +  ... + 0.99 + 1"
   ],
   "id": "3cdaca8d5f2fb671"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-13T04:20:13.300548Z",
     "start_time": "2025-09-13T04:20:13.296950Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# Initialize sum\n",
    "sum = 0\n",
    "\n",
    "# Add 0.01, 0.02, ..., 0.99, 1 to sum\n",
    "i = 0.01\n",
    "while i <= 1.0:\n",
    "    sum += i\n",
    "    i = i + 0.01\n",
    "\n",
    "# Display result\n",
    "print(\"The sum is\", sum)"
   ],
   "id": "b170f8308a5f91ad",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The sum is 49.50000000000003\n"
     ]
    }
   ],
   "execution_count": 24
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "- 预期得到50.5，但是……结果是49.5 。为什么呢？看一下循环变量 i 的值：\n",
    "```python\n",
    "0.01\n",
    "0.02\n",
    "0.03\n",
    "0.04\n",
    "0.05\n",
    "0.060000000000000005\n",
    "0.07\n",
    "0.08\n",
    "0.09\n",
    "0.09999999999999999\n",
    "0.10999999999999999\n",
    "0.11999999999999998\n",
    "0.12999999999999998\n",
    "0.13999999999999999\n",
    "0.15\n",
    "……………………\n",
    "0.9700000000000006\n",
    "0.9800000000000006\n",
    "0.9900000000000007\n",
    "1.0000000000000007\n",
    "```\n",
    "- 最后一个值是1.0000000000000007，本来这个值也应该加入到sum值中，但是因为它已经大于1了，最后一轮循环并未执行，所以结果差了1 。\n",
    "- 修改方法：将循环次数的控制变量改为整数。<font color='red'>python编程回避使用浮点数作为循环次数控制变量</font>"
   ],
   "id": "c77df603d5862b45"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-13T04:22:29.209419Z",
     "start_time": "2025-09-13T04:22:29.206028Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# Initialize sum\n",
    "sum = 0\n",
    "\n",
    "# Add 0.01, 0.02, ..., 0.99, 1 to sum\n",
    "i = 0.01\n",
    "for count in range(100):\n",
    "    sum += i\n",
    "    i = i + 0.01\n",
    "\n",
    "# Display result\n",
    "print(\"The sum is\", sum)\n",
    "\n",
    "# 输出： The sum is 50.50000000000003"
   ],
   "id": "5f20c38ae57841ed",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The sum is 50.50000000000003\n"
     ]
    }
   ],
   "execution_count": 25
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "",
   "id": "26bc469b13ad6436"
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "### 例子：判断是否为回文数\n",
    "\n",
    "- 回文数，即倒过来读与原数字相同的数，例如：12321"
   ],
   "id": "9d1b479a18c61c"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-13T04:23:19.838288Z",
     "start_time": "2025-09-13T04:23:15.613201Z"
    }
   },
   "cell_type": "code",
   "source": [
    "number = int(input('请输入一个整数：'))\n",
    "n = number\n",
    "m = 0\n",
    "\n",
    "# 从原数中从个位开始每次向高1位取一个数，然后让生成的新数*10再加上从原数中取出的这个数，重复以上动作，逐渐把原数中的每一位颠倒过来\n",
    "while n !=0:\n",
    "    m = m * 10 + n % 10\n",
    "    n //= 10\n",
    "\n",
    "if m == number:\n",
    "    print(number,'是回文数')\n",
    "else:\n",
    "    print(number,'不是回文数')"
   ],
   "id": "f182290ca67ef963",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "12321 是回文数\n"
     ]
    }
   ],
   "execution_count": 26
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "### 例子：打印九九乘法表\n",
    "\n",
    "- print()中加上end参数，可以输出后不换行，而是输出end的值。"
   ],
   "id": "e6d4b9e801f36ad"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-13T04:25:10.218043Z",
     "start_time": "2025-09-13T04:25:10.213104Z"
    }
   },
   "cell_type": "code",
   "source": [
    "for i in range(1,10):\n",
    "    for j in range(1,10):\n",
    "        k = i * j\n",
    "        if k < 10:\n",
    "            print(\" \",end=\"\") #如果是一位数，那么在前面加个空格，且不换行\n",
    "        print(k,end=\" \") # 输出一个数字，且不换行\n",
    "    print() # 仅换行"
   ],
   "id": "b5dbfc7f3513b4c6",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      " 1  2  3  4  5  6  7  8  9 \n",
      " 2  4  6  8 10 12 14 16 18 \n",
      " 3  6  9 12 15 18 21 24 27 \n",
      " 4  8 12 16 20 24 28 32 36 \n",
      " 5 10 15 20 25 30 35 40 45 \n",
      " 6 12 18 24 30 36 42 48 54 \n",
      " 7 14 21 28 35 42 49 56 63 \n",
      " 8 16 24 32 40 48 56 64 72 \n",
      " 9 18 27 36 45 54 63 72 81 \n"
     ]
    }
   ],
   "execution_count": 28
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "- 带格式版",
   "id": "9df2616dee2bf42f"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-13T04:25:42.168743Z",
     "start_time": "2025-09-13T04:25:42.164262Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# MultiplicationTable.py\n",
    "print(\"          Multiplication Table\")\n",
    "# Display the number title\n",
    "print(\"  |\", end = '')\n",
    "for j in range(1, 10):\n",
    "    print(\"  \", j, end = '')\n",
    "print() # Jump to the new line\n",
    "print(\"-----------------------------------------\")\n",
    "\n",
    "# Display table body\n",
    "for i in range(1, 10):\n",
    "    print(i, \"|\", end = '')\n",
    "    for j in range(1, 10):\n",
    "        # Display the product and align properly\n",
    "        print(format(i * j, '4d'), end = '')\n",
    "    print()# Jump to the new line"
   ],
   "id": "416db8f54c687e5c",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "          Multiplication Table\n",
      "  |   1   2   3   4   5   6   7   8   9\n",
      "-----------------------------------------\n",
      "1 |   1   2   3   4   5   6   7   8   9\n",
      "2 |   2   4   6   8  10  12  14  16  18\n",
      "3 |   3   6   9  12  15  18  21  24  27\n",
      "4 |   4   8  12  16  20  24  28  32  36\n",
      "5 |   5  10  15  20  25  30  35  40  45\n",
      "6 |   6  12  18  24  30  36  42  48  54\n",
      "7 |   7  14  21  28  35  42  49  56  63\n",
      "8 |   8  16  24  32  40  48  56  64  72\n",
      "9 |   9  18  27  36  45  54  63  72  81\n"
     ]
    }
   ],
   "execution_count": 29
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "### 例子：打印金字塔\n",
    "\n",
    "- 输入一个不大于9的正整数n，输出一个n行金字塔，如下所示\n",
    "\n",
    "```\n",
    "            1\n",
    "          1 2 1\n",
    "        1 2 3 2 1\n",
    "      1 2 3 4 3 2 1\n",
    "    1 2 3 4 5 4 3 2 1\n",
    "  1 2 3 4 5 6 5 4 3 2 1\n",
    "1 2 3 4 5 6 7 6 5 4 3 2 1\n",
    "```"
   ],
   "id": "13b2ac0f9d4a0b27"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-13T04:26:23.654790Z",
     "start_time": "2025-09-13T04:26:16.139123Z"
    }
   },
   "cell_type": "code",
   "source": [
    "n = int(input())\n",
    "for i in range(1,n+1):\n",
    "    for j in range((n-i)*2):\n",
    "        print(\" \",end=\"\")\n",
    "    for j in range(1,i+1):\n",
    "        print(j,end=' ')\n",
    "    for j in range(i-1,0,-1):\n",
    "        print(j,end=' ')\n",
    "    print()"
   ],
   "id": "db4c130551be8297",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "            1 \n",
      "          1 2 1 \n",
      "        1 2 3 2 1 \n",
      "      1 2 3 4 3 2 1 \n",
      "    1 2 3 4 5 4 3 2 1 \n",
      "  1 2 3 4 5 6 5 4 3 2 1 \n",
      "1 2 3 4 5 6 7 6 5 4 3 2 1 \n"
     ]
    }
   ],
   "execution_count": 30
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "### break 和 continue\n",
    "\n",
    "- break语句可以跳出 for 和 while 的循环体\n",
    "- 例：循环输入一个数字，输出其平方，直到输入0为止。"
   ],
   "id": "3d951550253dfa7e"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-13T04:27:30.329557Z",
     "start_time": "2025-09-13T04:27:10.984812Z"
    }
   },
   "cell_type": "code",
   "source": [
    "while True:\n",
    "    x = int(input())\n",
    "    if x == 0:\n",
    "        break\n",
    "    print(x**2)"
   ],
   "id": "6bcbbb91975ba32f",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "81\n",
      "16\n"
     ]
    }
   ],
   "execution_count": 31
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "- continue语句跳出当前轮循环，直接进行下一轮循环\n",
    "- 例：打印100以内的正整数中，不可以被7整除，数字中也不含7的整数。"
   ],
   "id": "11c93c18e86cf0c0"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-13T04:28:00.316136Z",
     "start_time": "2025-09-13T04:28:00.311899Z"
    }
   },
   "cell_type": "code",
   "source": [
    "for i in range(1,101):\n",
    "    if i % 7 == 0:\n",
    "        continue\n",
    "    if i % 10 == 7:\n",
    "        continue\n",
    "    if i // 10 == 7:\n",
    "        continue\n",
    "    print(i)"
   ],
   "id": "d0142b632a81e0a8",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n",
      "2\n",
      "3\n",
      "4\n",
      "5\n",
      "6\n",
      "8\n",
      "9\n",
      "10\n",
      "11\n",
      "12\n",
      "13\n",
      "15\n",
      "16\n",
      "18\n",
      "19\n",
      "20\n",
      "22\n",
      "23\n",
      "24\n",
      "25\n",
      "26\n",
      "29\n",
      "30\n",
      "31\n",
      "32\n",
      "33\n",
      "34\n",
      "36\n",
      "38\n",
      "39\n",
      "40\n",
      "41\n",
      "43\n",
      "44\n",
      "45\n",
      "46\n",
      "48\n",
      "50\n",
      "51\n",
      "52\n",
      "53\n",
      "54\n",
      "55\n",
      "58\n",
      "59\n",
      "60\n",
      "61\n",
      "62\n",
      "64\n",
      "65\n",
      "66\n",
      "68\n",
      "69\n",
      "80\n",
      "81\n",
      "82\n",
      "83\n",
      "85\n",
      "86\n",
      "88\n",
      "89\n",
      "90\n",
      "92\n",
      "93\n",
      "94\n",
      "95\n",
      "96\n",
      "99\n",
      "100\n"
     ]
    }
   ],
   "execution_count": 32
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "### 例子：求二个正整数的最大公约数",
   "id": "3ec24f23db774f6d"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-13T04:29:10.920558Z",
     "start_time": "2025-09-13T04:28:57.961668Z"
    }
   },
   "cell_type": "code",
   "source": [
    "#Prompt the user to enter two integers\n",
    "n1 = eval(input(\"Enter first integer: \"))\n",
    "n2 = eval(input(\"Enter second integer: \"))\n",
    "\n",
    "gcd = 1\n",
    "k = 2\n",
    "while k <= n1 and k <= n2:\n",
    "    if n1 % k == 0 and n2 % k == 0:\n",
    "        gcd = k\n",
    "    k += 1\n",
    "\n",
    "print(\"The greatest common divisor for\",\n",
    "    n1, \"and\", n2, \"is\", gcd)"
   ],
   "id": "b742452faa9843c2",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The greatest common divisor for 100 and 38 is 2\n"
     ]
    }
   ],
   "execution_count": 33
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "- 优化：从大往小找，找到的第一个符合条件的就是最大公约数",
   "id": "8fd58a15f21596d0"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-13T04:30:55.169424Z",
     "start_time": "2025-09-13T04:30:47.061Z"
    }
   },
   "cell_type": "code",
   "source": [
    "a = int(input())\n",
    "b = int(input())\n",
    "if a < b:\n",
    "    a,b = b,a\n",
    "for i in range(b,0,-1):\n",
    "    if a % i == 0 and b % i == 0:\n",
    "        break\n",
    "print(i)"
   ],
   "id": "9ce014cca531968c",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2\n"
     ]
    }
   ],
   "execution_count": 34
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "- 辗转相除法（又称**欧几里得算法**）求最大公约数",
   "id": "9a89b50d511da231"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-13T04:31:05.902577Z",
     "start_time": "2025-09-13T04:30:57.866783Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 辗转相除法\n",
    "a = int(input())\n",
    "b = int(input())\n",
    "if a < b:\n",
    "    a,b = b,a\n",
    "c = a % b\n",
    "while c!=0:\n",
    "    a = b\n",
    "    b = c\n",
    "    c = a % b\n",
    "print(b)"
   ],
   "id": "bb90199bc21c126d",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2\n"
     ]
    }
   ],
   "execution_count": 35
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "### 循环中的else\n",
    "\n",
    "- else如果与while或for语句配合使用，意思是当循环正常退出（即不是遇到break语句而退出）时，就会执行else子句。\n",
    "- 此语法为Python特有，其它语言（如C语言）一般没有将else用于循环语句中的语法。\n",
    "\n",
    " ### 例子：判断一个数是否为素数"
   ],
   "id": "4b84b057dfb6a7e9"
  },
  {
   "metadata": {},
   "cell_type": "code",
   "outputs": [],
   "execution_count": null,
   "source": [
    "number = int(input())\n",
    "isPrime = True\n",
    "for i in range(2,number):\n",
    "    if number % i == 0:\n",
    "        isPrime = False\n",
    "        break\n",
    "if isPrime:\n",
    "    print(number,\"is a prime number\")\n",
    "else:\n",
    "    print(number,\"is not a prime number\")"
   ],
   "id": "5a1277bfd07076d6"
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "- 循环中使用else，如果不执行break，则执行else",
   "id": "d659e334586ae256"
  },
  {
   "metadata": {},
   "cell_type": "code",
   "outputs": [],
   "execution_count": null,
   "source": [
    "number = int(input())\n",
    "for i in range(2,number):\n",
    "    if number % i == 0:\n",
    "        break\n",
    "else:\n",
    "    print(number,\"is a prime number\")"
   ],
   "id": "78fbdb947fa6dabc"
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "- 优化：其实循环结束的上限，不必达到 number-1，而是达到 math.ceil(number**0.5) 即可。原因：如果 n 是合数，则 n 必存在一个因数a小于等于n的平方根。证明如下：\n",
    "  - 设 m = math.ceil(n\\*\\*0.5)，如果存在 a,b 且 a<=b，使得 a\\*b = n，那么必然 a<=m。\n",
    "  - 反证法：假设a>m。因为a<=b，所以b>m，所以  a\\*b > m\\*\\*2 ，已知 n=a\\*b，代入上式，n > m\\*\\*2，与m的定义矛盾。"
   ],
   "id": "9bf97e85bdb6a0ff"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-14T03:35:44.187015Z",
     "start_time": "2025-09-14T03:35:40.780548Z"
    }
   },
   "cell_type": "code",
   "source": [
    "import math\n",
    "number = int(input())\n",
    "isPrime = True\n",
    "for i in range(2,math.ceil(number**0.5)+1):\n",
    "    if number % i == 0:\n",
    "        isPrime = False\n",
    "        break\n",
    "if isPrime:\n",
    "    print(number,\"is a prime number\")\n",
    "else:\n",
    "    print(number,\"is not a prime number\")"
   ],
   "id": "7a625aee27db08ed",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "7 is a prime number\n"
     ]
    }
   ],
   "execution_count": 1
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
